import axios from "axios";
import { Notification, MessageBox, Message } from 'element-ui'
import store from "../store";
axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
const request2 = axios.create({
    baseURL: "/dt-api",
    timeout: 50000 //请求超时，5000毫秒
});

//请求拦截器
request2.interceptors.request.use(
    config => {
        return config;
    },
    error => {
        //抛出异常
        return Promise.reject(error);
    }
);

//响应拦截器
request2.interceptors.response.use(
    response => {
        // 未设置状态码则默认成功状态
        const code = response.data.code || 200;
        // 获取响应信息
        const msg = response.data.msg;
        if (code === 401) {
            MessageBox.confirm('登录状态已过期，您可以继续留在该页面，或者重新登录', '系统提示', {
                confirmButtonText: '重新登录',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                store.dispatch('LogOut');
                location.href = '/login';
            })
        } else if (code === 500) {
            Message({
                message: msg,
                type: 'error'
            })
            return Promise.reject('error')
        } else if (code !== 200) {
            Notification.error({
                title: msg
            })
            return Promise.reject('error')
        } else {
            return response.data
        }
    },
    error => {
        console.log('err' + error)
        let { message } = error;
        if (message == "Network Error") {
            message = "后端接口连接异常";
        } else if (message.includes("timeout")) {
            message = "系统接口请求超时";
        } else if (message.includes("Request failed with status code")) {
            message = "系统接口" + message.substr(message.length - 3) + "异常";
        }
        Message({
            message: message,
            type: 'error',
            duration: 5 * 1000
        })
        return Promise.reject(error);
    }
);

export default request2; //导出自定义创建的axios对象